<?php
namespace MyAdmin\Controller;

use Think\Controller;

class AppsController extends CommonController
{
  public function __construct()
  {
    parent::__construct();
    $this->check_login();
  }

  public function xcx_edit()
  {
    $tpl = I('tpl');
    !$tpl && $tpl == 'xcx_edit';

    if ($tpl == 'xcx_msg_edit') {
      $title = '小程序消息模板配置';
    } elseif ($tpl == 'storage') {
      $title = '存储配置';
    } elseif ($tpl == 'sms') {
      $title = '短信配置';
    } elseif ($tpl == 'withdraw') {
      $title = '提现配置';
    } else {
      $title = '小程序配置';
    }

    if ($this->app_id) {
      $app = M('apps')->where("id = {$this->app_id}")->find();
      !$app['share_img'] && $app['share_img'] = 'Public/images/preview.jpg';
      !$app['shop_login_logo'] && $app['shop_login_logo'] = 'Public/images/preview.jpg';
      !$app['history_img'] && $app['history_img'] = 'Public/images/preview.jpg';
      !$app['user_img'] && $app['user_img'] = 'Public/images/preview.jpg';
      !$app['register_img'] && $app['register_img'] = 'Public/images/preview.jpg';
      !$app['login_img'] && $app['login_img'] = 'Public/images/preview.jpg';

      $this->assign("app", $app);
    }

    $this->assign('title', $title);
    $this->assign('tpl', $tpl);
    $this->display($tpl);
  }

  public function xcx_update()
  {
    $data = I('post.');
    !$data['tpl'] && $data['tpl'] = 'xcx_edit';

    if ($_FILES) {
      $files = file_upload($this->app_id);

      //TODO:
      if ($files) {
        if($_FILES['share_img']['name']){
          $data['share_img'] = $files[0];

          $_FILES['shop_login_logo']['name'] && $data['shop_login_logo'] = $files[1];
        }else{
          $_FILES['shop_login_logo']['name'] && $data['shop_login_logo'] = $files[0];
        }
      }
      if ($files) {
        if($_FILES['history_img']['name']){
           $data['history_img'] = $files[0];
           $_FILES['user_img']['name'] && $data['user_img'] = $files[1];
        }else{
           $_FILES['user_img']['name'] && $data['user_img'] = $files[0];
        }
      }

       if ($files) {
        if($_FILES['register_img']['name']){
          $data['register_img'] = $files[2];
          $_FILES['login_img']['name'] && $data['login_img'] = $files[3];
        }else{
          $_FILES['login_img']['name'] && $data['login_img'] = $files[2];
        }
      }
    }

    if (!$data['id'] && !$this->app_id) {
      $data = M('apps')->create($data);
      M('apps')->add($data);
    } else {
      $data['updated_at'] = $this->now_time;
      M('apps')->where("id = {$this->app_id}")->save($data);
    }

    $this->success('操作成功', U('Apps/xcx_edit')."&tpl={$data['tpl']}");
  }
}
